package com.llyb.chap08;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class CustomizeThreadPoolDemo {

    public static void main(String[] args) {
        int cpu = Runtime.getRuntime().availableProcessors(); //获取系统CPU数量。

        System.out.println(cpu);
        //创建线程池及7大参数
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                cpu+1,
                cpu*2,
                0,
                TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(5),
                Executors.defaultThreadFactory(),
                //new ThreadPoolExecutor.AbortPolicy() //直接抛异常
                //new ThreadPoolExecutor.CallerRunsPolicy() //交给调用者线程处理
                //new ThreadPoolExecutor.DiscardOldestPolicy() //丢弃队列等待最久的
                //new ThreadPoolExecutor.DiscardPolicy() //丢弃最新任务
                (runnable, poolExecutor)->{
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {}
                    poolExecutor.submit(runnable); //将任务重新提交回线程池来处理
                }
        );

        //java.util.concurrent.RejectedExecutionException
        for (int i = 1; i <= 20; i++) {
            String num = String.valueOf(i);
            //threadPoolExecutor.execute(new Runnable() {});  // Executor接口提供
            threadPoolExecutor.submit(()->{ //ExecutorService
                System.out.println(Thread.currentThread().getName() + "\t" + "--- i="+num);
                return "ok";
            });
        }

        //threadPoolExecutor.prestartCoreThread();//预先创建1个核心线程数量。
        threadPoolExecutor.prestartAllCoreThreads(); //预先创建所有核心线程数量。
    }
}
